﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace DeviceSync
{
	public static class WinAPICalls
	{
		[DllImport("coredll.dll", EntryPoint = "CeRunAppAtTime", SetLastError = true)]
		private static extern bool CeRunAppAtTime(string pwszAppName, UInt16[] lpTime);

		[DllImport("coredll.dll")]
		public static extern void SystemIdleTimerReset();

		[DllImport("coredll.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
		public extern static bool WinCESetSystemTime(UInt16[] time);

		public static void RestartInMins(int mins)
		{
			bool ok = CeRunAppAtTime(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase, ToSysTime(DateTime.Now.AddMinutes(mins)));
			if (!ok)
				throw new Exception("Failed to call CeRunAppAtTime()");
		}

		public static UInt16[] ToSysTime(DateTime dt)
		{
			UInt16[] s = new UInt16[8];
			s[0] = (UInt16)dt.Year;
			s[1] = (UInt16)dt.Month;
			s[2] = (UInt16)dt.DayOfWeek;
			s[3] = (UInt16)dt.Day;
			s[4] = (UInt16)dt.Hour;
			s[5] = (UInt16)dt.Minute;
			s[6] = (UInt16)dt.Second;
			s[7] = (UInt16)dt.Millisecond;

			return s;
		}
	}
}
